﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace SmartlForm.Common
{
    public static class TypeHelper
    {
        public static long ToLong(this object obj)
        {
            return obj == null ? 0 : Convert.ToInt64(obj);
        }


        public static int ToInt32(this object obj)
        {
            return obj == null ? 0 : Convert.ToInt32(obj);
        }


        public static string ToDateString(this DateTime date)
        {
            return date.ToString("yyyy-MM-dd hh:mm:ss");
        }


        /// <summary>
        /// 二进制序列化的方式进行深拷贝
        /// 确保需要拷贝的类里的所有成员已经标记为 [Serializable] 如果没有加该特性特报错
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T BinaryDeepCopy<T>(T t)
        {
            //创建二进制序列化对象
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())//创建内存流
            {
                //将对象序列化到内存中
                bf.Serialize(ms, t);
                ms.Position = 0;//将内存流的位置设为0
                return (T)bf.Deserialize(ms);//继续反序列化
            }
        }
    }
}
